<?php

//获取要更新的菜单信息
$roleMenuData = $route->bodyParams['roleMenuData'];

//获取当前角色ID
$roleId = $route->bodyParams['roleId'];

//查询当前角色原先所拥有的菜单数据
$roleSql = "SELECT * FROM sys_role_menu_middle WHERE rmm_orid = $roleId";
$roleData = $db->mysqlDB->query($roleSql);

//将要更新的菜单数据与原有菜单数据进行比对，如果更新的菜单数据中有原先的菜单数据，则用原先的操作Ids替换要更新的操作Ids
for($i=0;$i<count($roleMenuData);$i++){

    //要更新的菜单ID
    $updateRoleMenuId = $roleMenuData[$i]['menuId'];

    //比对原先的菜单
    for($k=0;$k<count($roleData);$k++){

        //原先菜单ID
        $oldRoleMenuId = $roleData[$k]['rmm_mid'];

        //原先菜单的Ids
        $oldRoleMenuIds = $roleData[$k]['rmm_apids'];

        //原先包含该菜单
        if($updateRoleMenuId === $oldRoleMenuId){

            //将原先的ids值赋值给要更新的ids，以保持原先的菜单操作
            $roleMenuData[$i]['actionIds'] = $oldRoleMenuIds;
            break;

        }
    }
}

//关闭事物自动提交
$db->mysqlDB->falseAutoCommit();

$deleteParams = array(
    "delete_where"       => "rmm_orid",
    "rmm_orid"           => $roleId,
    "isPhysicallyDelete" => "1"
);

//删除原有角色菜单
$R1 = $db->mysqlDB->automaticDelete($deleteParams)->delete("sys_role_menu_middle");

//拼接多添加语句
$addMoreSql = "INSERT INTO sys_role_menu_middle";

$keys = "(rmm_orid,rmm_mid,rmm_apids) VALUES";

$values = "";

for($i=0;$i<count($roleMenuData);$i++){

    $paramsOrid   = $roleId;
    $paramsMid    = $roleMenuData[$i]['menuId'];
    $paramsApids  = $roleMenuData[$i]['actionIds'];

    $tmpValue = "(";
    $tmpValue .= $paramsOrid.",'".$paramsMid."','".$paramsApids."'";
    $tmpValue .= "),";

    $values .= $tmpValue . "";

}

//拼接最终SQL
$addMoreSql .= $keys .= rtrim($values, ",");

//执行SQL
$R2 = $db->mysqlDB->queryTransaction($addMoreSql);

//判断两个操作是否执行成功
if ($R1 || !$R2) {
    $db->mysqlDB->rollBackCommint();
    $response->responseData(false);
}else{
    $db->mysqlDB->actionCommint();
    $db->mysqlDB->trueAutoCommit();
    $response->responseData(true);
}
